using B.S.RbacData.ErrorCode;
using ContentmanagementBase.Domain.Enums;
using ContentmanagementBaseRead.API.Applications.Commands.Popularizations;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using System.ComponentModel;
using System.Reflection;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Popularizations
{
    /// <summary>
    /// 获取疾病类型列表命令处理器
    /// </summary>
    public class GetDiseaseTypesCommandHandler : IRequestHandler<GetDiseaseTypesCommand, ApiResult<List<DiseaseTypeDto>>>
    {
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetDiseaseTypesCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        public GetDiseaseTypesCommandHandler(ILogger<GetDiseaseTypesCommandHandler> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理获取疾病类型列表命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<List<DiseaseTypeDto>>> Handle(GetDiseaseTypesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理获取疾病类型列表命令，科室ID：{DepartmentId}", request.DepartmentId);

                var diseaseTypes = new List<DiseaseTypeDto>();

                // 使用反射获取枚举值和描述
                var enumType = typeof(DiseaseTypeEnum);
                var enumValues = Enum.GetValues(enumType);

                foreach (var enumValue in enumValues)
                {
                    var value = (int)enumValue;
                    var name = enumValue.ToString();
                    
                    // 获取Description特性
                    var fieldInfo = enumType.GetField(name);
                    var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
                    var description = descriptionAttribute?.Description ?? name;

                    // 根据疾病类型确定所属科室
                    var departmentId = GetDepartmentIdByDiseaseType(value);

                    // 如果指定了科室ID，则只返回该科室的疾病类型
                    if (request.DepartmentId.HasValue && departmentId != request.DepartmentId.Value)
                    {
                        continue;
                    }

                    diseaseTypes.Add(new DiseaseTypeDto
                    {
                        Value = value,
                        Name = name,
                        Description = description,
                        DepartmentId = departmentId
                    });
                }

                _logger.LogInformation("疾病类型列表获取成功，共 {Count} 个疾病类型", diseaseTypes.Count);

                return new ApiResult<List<DiseaseTypeDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "疾病类型列表获取成功",
                    data = diseaseTypes
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取疾病类型列表过程中发生异常");
                return new ApiResult<List<DiseaseTypeDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取疾病类型列表异常：{ex.Message}",
                    data = new List<DiseaseTypeDto>()
                };
            }
        }

        /// <summary>
        /// 根据疾病类型获取对应的科室ID
        /// </summary>
        /// <param name="diseaseType">疾病类型值</param>
        /// <returns>科室ID</returns>
        private int GetDepartmentIdByDiseaseType(int diseaseType)
        {
            return diseaseType switch
            {
                // 内科疾病
                1 => (int)MedicalDepartmentEnum.内科, // 冠心病
                2 => (int)MedicalDepartmentEnum.内科, // 高血压
                3 => (int)MedicalDepartmentEnum.内科, // 心律失常
                4 => (int)MedicalDepartmentEnum.内科, // 糖尿病
                5 => (int)MedicalDepartmentEnum.内科, // 房颤

                // 外科疾病
                6 => (int)MedicalDepartmentEnum.外科, // 胆结石
                7 => (int)MedicalDepartmentEnum.外科, // 痔
                8 => (int)MedicalDepartmentEnum.外科, // 胰腺炎

                // 妇产科疾病
                9 => (int)MedicalDepartmentEnum.妇产科, // 乳腺炎

                // 儿科疾病
                10 => (int)MedicalDepartmentEnum.儿科, // 小儿肺炎
                11 => (int)MedicalDepartmentEnum.儿科, // 小儿哮喘
                12 => (int)MedicalDepartmentEnum.儿科, // 小儿咳嗽
                13 => (int)MedicalDepartmentEnum.儿科, // 小儿感冒

                // 其他疾病
                0 => (int)MedicalDepartmentEnum.未分类, // 未分类
                99 => (int)MedicalDepartmentEnum.其他, // 其他

                // 默认归类为其他
                _ => (int)MedicalDepartmentEnum.其他
            };
        }
    }
} 